package com.xuebank.nfe.nfecar.utils.loading;


import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatDialog;
import android.text.TextUtils;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.xuebank.nfe.nfecar.R;


/**
 * Created by Wind_Fantasy on 15/4/15.
 */
public class ProgressDailog extends AppCompatDialog {

    ImageView mGifView;
    TextView mContent;
    String mContentTxt;

    public ProgressDailog(Context context) {
        super(context);
    }

    public ProgressDailog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public ProgressDailog(Context context, int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getDelegate().requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.progress_circular);
        findViews();
        initViews();
    }


    private void findViews(){
        mContent = (TextView)findViewById(R.id.progress_content);
        mGifView = (ImageView)findViewById(R.id.progress_pv_circular);
    }

    private void initViews(){
        if(!TextUtils.isEmpty(mContentTxt) && null != mContent)
            mContent.setText(mContentTxt);
    }

    public ProgressDailog setContent(String str){
        this.mContentTxt = str;
        return this;
    }


    @Override
    public void dismiss() {
        try {//Can not perform this action after onSaveInstanceState?
            toggleAnim(false);
            super.dismiss();
        } catch (Exception e) {

        }
    }

    private void toggleAnim(boolean isStart){
        if(isStart){
//            Glide.with(getContext()).load(R.mipmap.ic_loading).asGif().into(mGifView);
            GifDrawable gifDrawable = (GifDrawable)mGifView.getDrawable();
            if(null != gifDrawable && !gifDrawable.isRunning())
                gifDrawable.start();
        }else {
            GifDrawable gifDrawable = (GifDrawable)mGifView.getDrawable();
            if(null != gifDrawable){
                gifDrawable.stop();
            }
            mGifView.setImageDrawable(null);
        }
    }

    @Override
    public void show() {
        super.show();
        toggleAnim(true);
    }

    @Override
    public void onDetachedFromWindow() {
        toggleAnim(false);
        super.onDetachedFromWindow();
    }

    @Override
    public void cancel() {
        toggleAnim(false);
        super.cancel();
    }
}
